package org.example.springboot.service;

import org.example.springboot.entity.User;
import org.example.springboot.exception.ServiceException;
import org.example.springboot.mapper.UserMapper;
import org.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能：
 * 作者：扫钢
 * 日期：2024/11/14 19:56
 */
@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    public void insertUser(User user) {
        userMapper.insert(user);
    }

    public void updateUser(User user) {
        userMapper.update(user);
    }

    public void deleteUser(Integer id) {
        userMapper.delete(id);
    }

    public void batchDeleteUser(List<Integer> ids) {
        for (Integer id : ids) {
            userMapper.delete(id);
        }
    }

    public List<User> selectAllUser() {
        return userMapper.selectAll();
    }

    public User selectUserById(Integer id) {
        return userMapper.selectById(id);
    }

    public List<User> selectUserByMore(String name, String phone) {
        return userMapper.selectByMore(name, phone);
    }

    public List<User> selectUserByMo(String name, String phone) {
        return userMapper.selectByMo(name, phone);
    }

    public Map<String, Object> selectUserByPage(String name, String phone, Integer pageNum, Integer pageSize) {
        Integer skipNum = (pageNum - 1) * pageSize;
        List<User> userList = userMapper.selectByPage(name, phone, skipNum, pageSize);
        Integer total = userMapper.selectByCountPage(name, phone);
        Map<String, Object> output = new HashMap<>();
        output.put("userList", userList);
        output.put("total", total);
        return output;
    }

    //验证用户账户是否合法
    public User login(User user) {
        // 根据用户输入的用户信息来查询数据库里已有的用户信息
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser == null) {
            throw new ServiceException("用户不存在");
        }
        if (!user.getPassword().equals(dbUser.getPassword())) {
            throw new ServiceException("用户名或密码错误");
        }
        // 生成token
        String token = TokenUtils.createToken(dbUser.getId().toString(), dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }

    public void register(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser != null) {
            throw new ServiceException("用户名已存在"); //效果等同于: serviceException(new ServiceException"用户名已存在")
        }
        user.setName(user.getUsername());
        userMapper.insert(user);
    }
}